package com.curator.install;

import cn.hutool.core.exceptions.ExceptionUtil;
import cn.hutool.core.io.resource.ResourceUtil;
import cn.hutool.json.JSONConfig;
import cn.hutool.json.JSONObject;
import com.curator.component.AbstractComponentInstall;
import com.curator.component.ComponentInstallFactory;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.InputStream;
import java.util.Map;

/**
 * 安装服务
 *
 * @author Jun
 * @date 2024/12/4
 */
public class InstallService {

    private static final Logger logger = LoggerFactory.getLogger(InstallService.class);

    /** 安装路径 */
    public static String INSTALL_PATH = "D:\\Program Files";

    /** 安装组件 按照字母顺序排序 */
    public static final JSONObject INSTALL_COMPONENT = new JSONObject(new JSONConfig().setNatureKeyComparator());

    /**
     * 安装
     *
     */
    public static void install() {
        for (Map.Entry<String, Object> entry : INSTALL_COMPONENT.entrySet()) {
            String component = entry.getKey();
            boolean installFlag = (boolean) entry.getValue();
            try {
                if (installFlag) {
                    InputStream inputStream = ResourceUtil.getStreamSafe("data/" + component + ".zip");
                    if (inputStream == null) {
                        logger.error("组件: {}不存在!", component);
                        continue;
                    }
                    logger.info("安装 {}", component);
                    AbstractComponentInstall installStrategy = new ComponentInstallFactory().getInstallStrategy(component);
                    if (installStrategy != null) {
                        installStrategy.componentInstall(inputStream, true);
                    } else {
                        logger.error("{} 对应安装策略不存在", component);
                    }
                }
            } catch (Exception e) {
                logger.error("组件: {} 安装出现异常: {}", component, ExceptionUtil.stacktraceToString(e));
            }
        }
    }
}
